package com.edu.convert;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class MyStringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        Date date = null;
        DateFormat dft = null;
        try {
            if (Pattern.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$", source)) {
                dft = new SimpleDateFormat("yyyy-MM-dd");
                date = dft.parse(source);
            }else if (Pattern.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$", source)) {
                dft = new SimpleDateFormat("yyyy/MM/dd");
                date = dft.parse(source);
            }else if (Pattern.matches("^\\d{4}年\\d{1,2}月\\d{1,2}日$", source)) {
                dft = new SimpleDateFormat("yyyy年MM月dd日");
                date = dft.parse(source);
            }else if (Pattern.matches("^\\d{4}\\\\\\d{1,2}\\\\\\d{1,2}$", source)) {
                dft = new SimpleDateFormat("yyyy\\MM\\dd");
                date = dft.parse(source);
            }else{
                throw new ClassCastException("无法将参数字符串:"+source+"转换为java.util.Date类型");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }
}
